import csv
import os
from datetime import datetime
import pandas as pd
class CSVStorage:
    def __init__(self,*args,output_dir='csv'):
        os.makedirs(output_dir, exist_ok=True)
        data_type = args[0]
        # self.filename = os.path.join(output_dir, f'{data_type}_{datetime.now().strftime("%Y%m%d")}.csv')
        self.filename = os.path.join(output_dir, f'{data_type}.csv')

    # def _ensure_header(self):
    #     if not os.path.exists(self.filename):
    #         with open(self.filename, 'w', newline='', encoding='utf-8') as f:
    #             writer = csv.writer(f)
    #             writer.writerow(['债券代码', '债券名称', '最新价', '溢价率', '成交量'])

    def save(self, pd_data):
        pd_data.to_csv(self.filename,index=False)

    def query_all(self):
        if not os.path.exists(self.filename):
            return []
        
        with open(self.filename, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            return [row for row in reader]